package cn.liziguo;

import cn.liziguo.utils.Captcha;
import cn.liziguo.utils.CaptchaUtils;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.filechooser.FileSystemView;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * @author Liziguo
 * @date 2021/12/19 23:32
 */
public class Test extends JFrame {

    private BufferedImage image;

    public Test() {
        setResizable(false);//用户不能随意调节窗口大小
        reImage();
        setSize(image.getWidth(), image.getHeight());//设置大小
        setLocationRelativeTo(null);//窗口居中
        setDefaultCloseOperation(3);//x掉后彻底退出程序
        setAlwaysOnTop(true);//窗口始终在最上方
        setUndecorated(true);//去除修饰（去除窗口边框、最大化、最小化、关闭按钮等）
        //添加一个键盘事件 按Esc关闭窗口 F5重新生成验证码
        addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == 27) {
                    //27是键盘Esc的Ascii码
                    System.exit(0);
                } else if (e.getKeyCode() == 116) {
                    //116是键盘F5的Ascii码
                    reImage();
                }
            }
        });
        addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                reImage();
            }
        });
        setVisible(true);//显示
    }

    private void reImage() {
        final String code = CaptchaUtils.randomCode(4);//随机生成4位数字符串
        //最佳宽高计算公式 height = fontSize  width = height * len * 0.75
//        final Captcha v = CaptchaUtils.create(code, 160, 60, 60);//生成图形验证码
        final Captcha v = CaptchaUtils.create(code, 1200, 400, 400);//生成图形验证码
//        final Captcha v = CaptchaUtils.create("我好想你", 1920, 1080, 400);//生成图形验证码
        image = v.image;
        setSize(image.getWidth(), image.getHeight());//设置大小
        setLocationRelativeTo(null);//窗口居中
        repaint();//重绘
        System.out.println("验证码信息:");
        System.out.println("id:" + v.id);
        System.out.println("code:" + v.code);
        System.out.println("lowerCode:" + v.getLowerCode());
        System.out.println("upperCode:" + v.getUpperCode());
        System.out.println("imageBase64Code:" + v.toBase64Code());
        //获取桌面路径
        File file = new File(FileSystemView.getFileSystemView().getHomeDirectory().getAbsolutePath() + "/captcha.png");
        //把这张验证码保存到桌面
        try {
            ImageIO.write(v.image, "png", file);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        //这里我们重写一下paint方法 把图片画出来
        g.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
    }

    public static void main(String[] args) throws IOException {
        new Test();
    }
}

